"use client"

import { useConfigStore } from "@/stores"
import { useRef, useEffect } from "react"

export function Sidebar() {
  const { categories, activeTab, setActiveTab } = useConfigStore()
  const navContainerRef = useRef<HTMLDivElement>(null)

  const handleTabClick = (index: number) => {
    setActiveTab(index)
  }

  // 添加鼠标滚轮横向滚动功能和边界垂直滚动功能
  useEffect(() => {
    const navContainer = navContainerRef.current
    if (!navContainer) return

    const handleWheel = (e: WheelEvent) => {
      // 始终阻止默认行为，避免与其他滚动逻辑冲突
      e.preventDefault()
      
      const isScrollingRight = e.deltaY > 0  // 向右/向下滚动
      const isScrollingLeft = e.deltaY < 0   // 向左/向上滚动
      
      // 边界检测
      const isAtRightBoundary = navContainer.scrollLeft + navContainer.clientWidth >= navContainer.scrollWidth - 1
      const isAtLeftBoundary = navContainer.scrollLeft <= 0
      
      // 情况1：在右边界且继续向右滚动 → 手动向下滚动页面
      if (isAtRightBoundary && isScrollingRight) {
        window.scrollBy({
          top: e.deltaY * 0.5, // 保持与水平滚动一致的速度
          behavior: 'smooth'
        })
        return
      }
      
      // 情况2：在左边界且继续向左滚动 → 手动向上滚动页面  
      if (isAtLeftBoundary && isScrollingLeft) {
        window.scrollBy({
          top: e.deltaY * 0.5, // 保持一致的滚动速度
          behavior: 'smooth'
        })
        return
      }
      
      // 情况3：正常水平滚动（中间区域或向内滚动）
      const scrollAmount = e.deltaY * 0.5 // 调整滚动速度
      navContainer.scrollLeft += scrollAmount
    }

    // 添加事件监听器
    navContainer.addEventListener('wheel', handleWheel, { passive: false })

    // 清理函数
    return () => {
      navContainer.removeEventListener('wheel', handleWheel)
    }
  }, [])

  return (
    <nav className="top-navigation">
      <div 
        className="top-nav-container" 
        ref={navContainerRef}
      >
        <ul className="horizontal-nav-tabs">
          {categories.map((category, index) => (
            <li 
              key={index}
              className={`nav-tab-item ${activeTab === index ? 'active' : ''}`}
              data-tab={`tab${index}`}
              onClick={() => handleTabClick(index)}
            >
              <span className="tab-title">{category.title}</span>
              <div 
                className="active-line" 
                style={{width: activeTab === index ? '100%' : '0'}}
              ></div>
            </li>
          ))}
        </ul>
      </div>
    </nav>
  )
}
